package com.web.exiaodao.remote.controller;

import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.Order;
import com.web.exiaodao.business.entity.WalletRechargeRecord;
import com.web.exiaodao.business.entity.WalletWithdrawRecord;
import com.web.exiaodao.business.repository.OrderRepository;
import com.web.exiaodao.remote.service.*;
import com.web.exiaodao.remote.vo.UserVo;
import com.web.exiaodao.remote.vo.WalletRechargeRecordVo;
import com.web.exiaodao.remote.vo.WalletTradeRecordVo;
import com.web.exiaodao.remote.vo.WalletWithdrawRecordVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.util.Identities;
import com.web.webstart.base.util.Validator;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.YamlUtils;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author zhanglin
 * @version V1.0
 * @Title: ApiWalletTradeRecordController.java
 * @Package com.web.exiaodao.remote.controller
 * @Description: 钱包-交易记录,交易明细信息接口
 * @date 2017-01-22 18:34:39
 */
@Api(value = "wallet", description = "钱包|交易记录|交易明细接口", position = 10)
@Controller
@RequestMapping("/api/wallet")
public class ApiWalletController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ApiWalletController.class);

    @Autowired //交易记录
    private ApiWalletTradeRecordService walletTradeRecordService;
    @Autowired //充值
    private ApiWalletRechargeRecordService walletRechargeRecordService;
    @Autowired //提现
    private ApiWalletWithdrawRecordService walletWithdrawRecordService;

    @Autowired
    private ApiUserService userService;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private ApiOrderService orderService;

    /**
     * @return
     * @Title: findWalletTradeRecordList
     * @Description: 查询所有钱包-交易记录,交易明细信息
     * @see JConstant.WalletTradeType
     */
    @ApiOperation(value = "查询所有交易记录,交易明细", notes = "查询所有钱包-交易记录,交易明细信息,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value = "findWalletTradeRecordList", method = RequestMethod.POST)
    public XaResult<List<WalletTradeRecordVo>> findWalletTradeRecordList(
            @ApiParam("充值用户,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("交易类型,字段名:tradeType") @RequestParam(value = "tradeType", required = false) Integer tradeType,
            @ApiParam("页号,字段名:nextPage,默认0,从第0页开始") @RequestParam(defaultValue = "0", required = false) Integer nextPage,
            @ApiParam("页长,字段名:pageSize,默认10") @RequestParam(defaultValue = "10", required = false) Integer pageSize
    ) throws Exception {
        XaResult<List<WalletTradeRecordVo>> xr = new XaResult<List<WalletTradeRecordVo>>();
        Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, "[{property:'createTime',direction:'DESC'}]");
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith("{'search_EQ_userId':'" + userId + "'}", "search_");
        if (tradeType != null) {
            filterParams.put("EQ_tradeType", tradeType);
        }
        xr = walletTradeRecordService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable);
        return xr;
    }

    /**
     * @return
     * @Title: 钱包支付
     */
    @ApiOperation(value = "钱包支付", notes = "钱包支付,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "walletPay", method = RequestMethod.POST)
    public XaResult<WalletTradeRecordVo> walletPay(
            @ApiParam("充值用户,字段名:payPassword") @RequestParam(value = "payPassword") String payPassword,
            @ApiParam("充值用户,字段名:orderNo") @RequestParam(value = "orderNo") String orderNo,
            HttpServletRequest request
    ) throws Exception {
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();

        Order order = orderRepository.findByOrderNoAndStatusNot(orderNo, XaConstant.Status.delete);
        if (XaUtil.isEmpty(order)) {
            xr.error("订单不存在：" + orderNo);
            return xr;
        }
        UserVo userVo = userService.findOne(order.getUserId()).getObject();
        if (!userVo.getPayPassword().equals(payPassword)) {
            xr.error("交易密码错误,请重试！");
            return xr;
        }
        if (order.getOrderTotalPirce() > userVo.getBalance()) {
            xr.error("钱包余额不足，请先充值获取改用其他方式支付；余额为：" + userVo.getBalance());
            return xr;
        }
        String price = order.getOrderTotalPirce().toString();
        orderService.modifyOrder(orderNo, price, null, JConstant.PayType.WALLET);
        return xr;
    }

    /**
     * @return
     * @Title: 钱包充值
     */
    @ApiOperation(value = "钱包充值", notes = "钱包充值,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "recharge", method = RequestMethod.POST)
    public XaResult<WalletRechargeRecordVo> recharge(
            @ApiParam("充值用户,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("充值金额,字段名:rechargeMoney") @RequestParam(value = "rechargeMoney") Double rechargeMoney,
            @ApiParam("充值方式,默认微信0；支付宝1;银联2，选填,字段名:rechargeMethod") @RequestParam(value = "rechargeMethod", required = false, defaultValue = "" + JConstant.PayType.ALIPAY) Integer rechargeMethod,
            HttpServletRequest request
    ) throws Exception {
        XaResult<WalletRechargeRecordVo> xr = new XaResult<>();
        WalletRechargeRecord model = new WalletRechargeRecord();

        //验证用户是否存在
        userService.findOne(userId);

        if (rechargeMethod != JConstant.PayType.ALIPAY) {
            xr.error("充值目前只支持支付宝！");
            return xr;
        }
        if (rechargeMoney <= 0) {
            xr.error("请输入正确的充值金额！");
            return xr;
        }

        model.setUserId(userId);
        model.setRechargeMoney(rechargeMoney);
        model.setRechargeOrderNo(Identities.getRechargeOrderNo());//生成充值订单
        model.setRechargeMethod(rechargeMethod);
        model.setRechargeStatus(JConstant.WalletRechargeStatus.RECHARGE_ING);
        xr = walletRechargeRecordService.createModel(model);
        return xr;
    }

    /**
     * @return
     * @Title: save
     * @Description: 钱包提现
     */
    @ApiOperation(value = "钱包提现", notes = "钱包提现,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "withdraw", method = RequestMethod.POST)
    public XaResult<WalletWithdrawRecordVo> withdraw(
            @ApiParam("提现用户,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("提现金额,字段名:withdrawMoney") @RequestParam(value = "withdrawMoney") Double withdrawMoney,
            @ApiParam("提现支付宝账号,字段名:alipayAccount") @RequestParam(value = "alipayAccount") String alipayAccount,
            @ApiParam("提现支付宝收款账号姓名,字段名:alipayUsername") @RequestParam(value = "alipayUsername") String alipayUsername,
            HttpServletRequest request
    ) throws Exception {
        XaResult<WalletWithdrawRecordVo> xr = new XaResult<WalletWithdrawRecordVo>();

        //验证用户是否存在
        XaResult<UserVo> userXr = userService.findOne(userId);
        if (withdrawMoney <= 0) {
            xr.error("请输入正确的提现金额！");
            return xr;
        }
        if (userXr.getObject().getBalance() < withdrawMoney) {
            xr.error("您目前最大可以提现:" + userXr.getObject().getBalance() + "!");
            return xr;
        }
        double withdrawMoneyMin = (double) YamlUtils.yaml2Map("data.yml").get("withdrawMoneyMin");
        if (withdrawMoney < withdrawMoneyMin) {
            xr.error("提现至少"+withdrawMoneyMin+"！");
            return xr;
        }
        if (XaUtil.isEmpty(alipayAccount)) {
            xr.error("提现支付宝账号不能为空！");
            return xr;
        }
        if (alipayAccount.contains("^")) {
            xr.error("提现支付宝账号不能包含特殊字符！");
            return xr;
        }
        if (!Validator.isEmail(alipayAccount) && !Validator.isMobile(alipayAccount)) {
            xr.error("支付宝账号只能为手机号或者邮箱！");
            return xr;
        }
        if (XaUtil.isEmpty(alipayUsername)) {
            xr.error("提现支付宝收款账号姓名不能为空！");
            return xr;
        }
        if (alipayUsername.contains("^")) {
            xr.error("提现支付宝收款账号姓名不能为空不能包含特殊字符！");
            return xr;
        }
        WalletWithdrawRecord model = new WalletWithdrawRecord();
        model.setUserId(userId);
        model.setWithdrawMoney(withdrawMoney);
        model.setAipayAccount(alipayAccount);
        model.setAlipayUsername(alipayUsername);
        model.setWithdrawStatus(JConstant.WalletWithdrawStatus.WITHDRAW_ING);
        model.setWithdrawTradeNo(Identities.getBatchOrderNo());

        xr = walletTradeRecordService.widthdrawApplyForring(model);

        return xr;
    }

}

